package com.action.boot.mongo.mongo_template.dao;

import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.lookup;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;

/**
 * Created by Wuxiang on 2017/11/11.
 *
 * 涉及的 collection
 *
 * 该方法包含四个参数，
 fromCollection => 需要连接的Collection
 local => 当前Collection中需要连接的字段
 from => 外连Collection中连接查询的字段
 joinedOutput => 查询结果输出到此字段中
 */
@Component
public class JoinDao {
    @Autowired
    MongoTemplate mongoTemplate;

    private static String collection1 = "patient";
    private static String collection2 = "recordInfo";

    public List<DBObject> selectAll() {
        Aggregation aggregation=newAggregation(
                lookup(collection1,"patientName","name","patient")
        );

        AggregationResults<DBObject> results = mongoTemplate.aggregate(aggregation, collection2, DBObject.class);

        List<DBObject> list = results.getMappedResults();
        return list;
    }

    public void initLeftJoin(List<DBObject> dbObjects1,List<DBObject> dbObjects2) {
        mongoTemplate.dropCollection(collection1);
        mongoTemplate.insert(dbObjects1, collection1);

        mongoTemplate.dropCollection(collection2);
        mongoTemplate.insert(dbObjects2, collection2);
    }
}
